


// v7
// echart 5.5.0
(() => {

  function isArray(obj) {
    return typeof obj === "object" && Array.isArray(obj);
  }

  // const u1="http://sun_water70000.esp32.lan/sun_water_history";
  // const u2="http://sun_water70000.esp32.lan/sun_water_history";

  const baseUrl = "http://op.lan:81/cgi-bin/sun_water70000.sh";
  const historyUrl = baseUrl + "?json=history"
  let myChart;


  let gen_option = (x, y1, y2) => {
    const red = 'rgba(255,100,100,10)';
    const blue = 'rgb(0, 167, 208)';
    let barWidth;
    if (y2.length < 10) {
      barWidth = '25%';
    } else if (y2.length < 50) {
      barWidth = '50%';
    } else if (y2.length < 100) {
      barWidth = '75%';
    } else {
      barWidth = '88%';
    }

    return {
      tooltip: {
        trigger: 'axis',
        textStyle: {
            fontSize: 22
        },
        /*axisPointer: {
          type: 'cross'
        }*/
        axisPointer: {
            type: 'shadow'
        }
      },
      xAxis: {
        type: 'category',
        boundaryGap: true,
        axisLine: {
          lineStyle: {
            color: "gray",
          },
        },
        axisLabel: {
          color: "gray",
          rotate: 60,
        },
        axisTick: {
          show: false
        },
        data: x
      },
      yAxis: [{
        type: 'value',
        position: 'left',
        name: '🌡️℃',
        min: 0,
        max: 110,
        interval: 10,
        axisPointer: {
            snap: true
        },
        splitLine: {
          show: false,
        },
        axisLine: {
          show: false,
          lineStyle: {
            color: red
          }
        },
        axisLabel: {
          color: red,
          formatter: function (p) {
            if (p <= 100) return p;
          }
        },
        axisTick: {
          show: false
        },
      }, {
        type: 'value',
        position: 'right',
        name: '💧',
        min: 0,
        max: 11,
        interval: 1,
        axisPointer: {
            snap: true
        },
        axisLine: {
          show: false,
          lineStyle: {
            color: blue,
          }
        },
        axisTick: {
          show: false
        },
        axisLabel: {
          color: blue,
          formatter: function (p) {
            if (p > 0 && p <= 4) return p;
          }
        }
      },
      ],
      series: [
        {
          //   name: '温度🌡️',
          type: 'line',
          symbolSize: 1,
          smooth: true,
          // prettier-ignore
          yAxisIndex: 0,
          data: y1,
          lineStyle: {
            color: red
          },
          //  markArea: {
          itemStyle: {
            color: red
          }
          //}
        },
        {
          // name: '水位📶',
          type: 'bar',
          yAxisIndex: 1,
          data: y2,
          barWidth: barWidth,
          itemStyle: {
            color: blue,
          }
        }
      ]
    };
  }


  let currentTime = () => {
    let date = new Date();
    return date.getTime();
  }
  const cache_key = "__history__";

  let get_from_cache = () => {

    try {
      let data = localStorage.getItem(cache_key);
      if (!data) return null;
      data = JSON.parse(data);
      if (currentTime() - data.timestamp > 3 * 60 * 1000) {
        return null;
      }
      console.log("[cache] got");
      return data.data;
    } catch (e) {
      return null;
    }
  }

  let save_cache = (data) => {
    try {
      if (!data) return;
      console.log("[cache] saved");
      localStorage.setItem(cache_key, JSON.stringify({
        timestamp: currentTime(),
        data: data,
      }));
    } catch (e) {
    }
  }

  const MAX_RETRY_COUNT = 3;

  let retry_count = 0;

  const could_skip = (i,length, skipN) => {
    try {
      if (skipN > 0 && i % skipN != 0) {
        if (i < length - 10) {
          // 保留 最近的 9~10个数据!!!

          return true;
        }
      }
    } catch (e) {

    }
    return false;
  }

  let fetch_data = (u, on_success) => {
    console.log("fetch_data");
    fetch(u, {
      method: "GET",
      cache: "no-store",
      keepalive: false,
    })
      .then((d) => {
        return d.json();
      })
      .then((j) => {
        console.log("fetch_data", j);
        let data = [];
        let yestoday = j["yestoday"];
        let today = j["today"];
        if (isArray(yestoday)) {
          data.push(...yestoday);
        }
        if (isArray(today)) {
          data.push(...today);
        }

        if (data.length > 0) {
          save_cache(data);
          on_success(data);
        }
      })
      .catch((e) => {
        // if(u==u1){
        //     fetch_data(u2,on_success);
        // }
        console.log("[E] fetch_data err", e);
        retry_count++;
        if (retry_count < MAX_RETRY_COUNT) {
          setTimeout(() => {
            fetch_data(u, on_success);
          }, 3000);
        }
      })
  }

  let paintEchart = (data) => {
    console.log("[i] data=", data);
    // if(data.length>20){
    //     data=data.slice(0,20);
    // }
    let d_time = [];
    let d_temprature = [];
    let d_height = [];
    let skip = -1;
    if (data.length > 75 && data.length < 150) {
      skip = 2;
    } else if (data.length > 100) {
      skip = parseInt(data.length / 100) + 3;
    }

    console.log(`[i] data.length=${data.length} skip=${skip}`);
    let pre_h = -1;
    let pre_th = -11;
    let pre_tt = -11;
    for (let i = 0; i < data.length; i++) {
      // data.forEach(el => {
      // hour, t,h
      let el = data[i];
      let t = null;
      let tt = null;
      let h = null;
      let th = null;
      let time = null;
      try {
        if (isArray(el)) {
          t = el[2];
          tt = el[3]||-1;
          h = el[4];
          th = el[5]||-1;
          time = el[0] + ":" + (el[1] > 9 ? "" : "0") + el[1];
        } else {
          t = el.temperature_float;
          tt = el.target_t||-1;
          h = el.height;
          th = el.target_h||-1;
          time = el.time;
          if (time.lastIndexOf(":") != time.indexOf(":")) {
            time = time.substring(0, time.lastIndexOf(":"));
          }
        }

        if(could_skip(i,data.length,skip)){
          if (h == pre_h && tt==pre_tt && th==pre_th) {
            // console.log("[i] skipped", i, el);
            continue;
          }
        }

        if (t && h && time) {
          if(tt>10) time=time+"(🌡️"+tt.toFixed(0)+")";
          if(th>0) time=time+"(💧"+th.toFixed(0)+")";
          d_time.push(time);
          d_temprature.push(t.toFixed(1));
          d_height.push(h);
          pre_h = h;
          pre_th = th;
          pre_tt = tt;
        }
      } catch (e) {
        // console.log(e);
      }
      // });
    };

    console.log(d_time);
    console.log(d_temprature);
    console.log(d_height);

    let option = gen_option(d_time, d_temprature, d_height);

    option && myChart.setOption(option);

    window.addEventListener('resize',()=>{
      myChart.resize();
    });

  }

  let mainJob = (block) => {
    myChart = echarts.init(block);
    // check cache
    let cache_data = get_from_cache();
    if (cache_data) {
      paintEchart(cache_data);
    } else {
      fetch_data(historyUrl, paintEchart);
    }
  }


  let tryCount = 0;
  let task = () => {
    tryCount++;
    let block = document.getElementById("echart_block");
    if (block) {
      console.log("started");;
      mainJob(block)
    } else if (tryCount < 20) {
      setTimeout(task, 1000);
    }
  }


  task();


})();

